package ltd.followkba.task;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;


import com.kcbsdk.AFileBase;
import com.kcbsdk.MyWorks.AAccountType;
import com.kcbsdk.MyWorks.AFileInfo;
import com.kcbsdk.MyWorks.AGiftBean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.MPAGE;
import ltd.advskin.utils.SysTools;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.MainPage;
import ltd.followkba.W;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;


public class TaskService extends Service {
    public final static int NOTIFI_ID = 0x0250;

    private NotificationManager mManager;
    private Notification mNotification;
    private NotificationCompat.Builder mBuilder;
    public int[] gSuccessQty;
    public int gSuccesslAll;
    public int gSuccesslMemory;
    public int gAppType;

    private int[] tab_ViewID = {R.id.ivIconService, R.id.tvNameService, R.id.tvStateService};


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MLOG("TaskService mBroadcastReceiver onReceive "+intent.getAction());
            String gsLocal_1 = intent.getAction();
            String gsLocal_2;
            for (int counter = 0; counter < tab_ViewID.length; counter++){
                gsLocal_2 = String.format("%s_%d", "task_service", counter);
                if (gsLocal_2.equals(gsLocal_1)) {
                    onButton(context, counter);
                    break;
                }
            }
        }
    };
    
    @Override
    public void onCreate() {
        super.onCreate();

        String channelId = "channelId";
        String channelName = "channelName";
        String channelDescription = "channelDescription";
        mManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
//            channel.enableLights(true);                 // 设置开启指示灯，如果设备有的话
//            channel.setLightColor(Color.RED);           // 设置指示灯颜色
//            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 600});  // 设置震动频率

            channel.setShowBadge(true);                 // 设置是否显示角标
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);   // 设置是否应在锁定屏幕上显示此频道的通知
            channel.setDescription(channelDescription);     // 设置渠道描述
            channel.setBypassDnd(true);                     // 设置是否绕过免打扰模式
            channel.setSound(null, null); // 设置通知出现时声音，默认通知是有声音的

            mManager.createNotificationChannel(channel);
            mBuilder = new NotificationCompat.Builder(MRAM.mContext, channelId);
            mBuilder.setSmallIcon(R.mipmap.ic_launcher);
            mBuilder.setOngoing(true);
        }else{
            mNotification = new Notification(R.mipmap.ic_launcher, "", System.currentTimeMillis());
        }

        RemoteViews remoteViews = getRemoteViews();
        IntentFilter intentFilter = new IntentFilter();
        PendingIntent pendIntent;
        String gsLocal_1;
        for (int counter = 0; counter < tab_ViewID.length; counter++){
            gsLocal_1 = String.format("%s_%d", "task_service", counter);
            intentFilter.addAction(gsLocal_1);
            pendIntent = PendingIntent.getBroadcast(this, 0, new Intent(gsLocal_1), 0);
            remoteViews.setOnClickPendingIntent(tab_ViewID[counter], pendIntent);
        }

        Bitmap bitmap = BitmapFactory.decodeResource(getApplication().getResources(), R.mipmap.ic_launcher);
        remoteViews.setImageViewBitmap(tab_ViewID[0], bitmap);

        registerReceiver(mBroadcastReceiver, intentFilter);       // 注册广播
        if (mNotification != null) {
            if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1){
                mNotification.bigContentView = remoteViews;
            }
            mNotification.contentView = remoteViews;
            startForeground(NOTIFI_ID, mNotification);    // 前台运行
        }
        if (mBuilder != null && MRAM.mContext != null){
            startForeground(NOTIFI_ID, mBuilder.build());    // 前台运行
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                MLOG("Thread.currentThread B "+Thread.currentThread().getPriority());
                Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                MLOG("Thread.currentThread C "+Thread.currentThread().getPriority());
                long s10 = System.currentTimeMillis();
                long tick = s10 - (10 * (60*1000));
                while (!MAPP.threadStop){
                    MSLEEP(2000);
//MLOG("onTime2sA A");
                    onTime2s();
//MLOG("onTime2sA B");
                    if ((System.currentTimeMillis() - tick) > (1 * (60 * 1000))) {
                        tick = System.currentTimeMillis();
//MLOG("onTime2sA C");

//MLOG("onTime2sA D");
                    }
                }
            }
        }).start();
        MLOG("TaskService onCreateA "+MAPP.threadStop);
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
    }


    private void onTime2s(){
        onTimeMainPage(true);
        if (MRAM.mActivity != null){
            MRAM.mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onTimeMainPage(false);
//MLOG(String.format("gSuccessQtyA a %s", MAPP.gSuccessQty != null?MAPP.gSuccessQty.length:0));
                    if (MAPP.gSuccessQty != null) {
                        if (gSuccesslMemory != 0 && MAPP.gSuccesslAll != gSuccesslAll) {
                            RemoteViews remoteViews = getRemoteViews();
                            String text = String.format("共成功%s总%s", gSuccesslAll, gSuccesslMemory);
                            remoteViews.setTextViewText(tab_ViewID[1], text);
                            showNotification();
                            MAPP.gSuccesslAll = gSuccesslAll;
                            StringBuffer stringBuffer = new StringBuffer();
                            for (int index = 0; index < MAPP.gSuccessQty.length; index++) {
//MLOG(String.format("gSuccessQtyA b %s %s %s", index, gSuccessQty[index], MAPP.mWorksName[gAppType]));
                                int appType = gAppType;
                                if (++gAppType >= MAPP.gSuccessQty.length){
                                    gAppType = 0;
                                }
                                MAPP.gSuccessQty[appType] = gSuccessQty[appType];
                                if (gSuccessQty[appType] > 0) {
                                    stringBuffer.append(MAPP.mWorksName[appType]);
                                    stringBuffer.append(String.format("%s ", MAPP.gSuccessQty[appType]));
                                    break;
                                }
                            }
                            text = stringBuffer.toString();
                            if (MAPI.isEmpty(text)){
                                text = "还没有成功";
                            }
                            remoteViews.setTextViewText(tab_ViewID[2], text);
                        }
                    }
                }
            });
        }

        if (MAPP.gSuccessQty != null && MAPP.mTaskEach != null) {
            gSuccessQty = new int[MAPP.gSuccessQty.length];
            gSuccesslAll = 0;
            gSuccesslMemory = 0;
            int qty = 0;
            for (int tabTyp = 0; tabTyp < MAPP.mWorksType.length; tabTyp++) {
                if (MAPP.mTaskEach[tabTyp] != null && MAPP.mTaskEach[tabTyp].length > 1) {                        // 注意第0个不是正常的任务
                    for (int index = 1; index < MAPP.mTaskEach[tabTyp].length; index++) {      // 先将所有运行的停止掉
                        gSuccessQty[tabTyp] += MAPP.mTaskEach[tabTyp][index].SuccessQty;
                        gSuccesslAll += MAPP.mTaskEach[tabTyp][index].SuccessQty;
                        qty += MAPP.mTaskEach[tabTyp][index].mBDbsAccount.SuccessQty;
                    }
                }
            }
            gSuccesslMemory = qty;
        }
    }

    private void onTimeMainPage(boolean isThread){
        if (MPAGE.mPageCurrent instanceof MainPage) {
            MainPage mainPage = (MainPage) MPAGE.mPageCurrent;
            mainPage.onTime(isThread);
        }
    }



    private RemoteViews getRemoteViews (){
        if (mNotification != null && mNotification.contentView != null){
            return mNotification.contentView;
        }
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.task_service);
        if (mBuilder != null){
            mBuilder.setContent(remoteViews);
        }
        return remoteViews;
    }
    private void showNotification(){
        try {
            if (mManager != null) {
                if (mNotification != null) {
                    mManager.notify(NOTIFI_ID, mNotification);
                }
                if (mBuilder != null) {
                    mManager.notify(NOTIFI_ID, mBuilder.build());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            MLOGE("showNotification Error "+e.toString());
        }

    }



    private void onButton(Context context, int key) {
        MLOG("onButtonA A " + key);
        SysTools sysTools = new SysTools();
        sysTools.collapseStatusBar(context);    // 收起通知栏
        Intent intent = new Intent(context, MRAM.mActivity.getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  // 必须添加，避免重复打开
        context.startActivity(intent);
    }
    
}
